﻿using System;
using System.Collections.Generic;
using IBatisNet.DataMapper;
using IBatisNet.DataMapper.MappedStatements;
using IBatisNet.DataMapper.Scope;

namespace ConsoleApp.MyBatis
{
    public class MyBatis_Repository
    {
        public ISqlMapper SqlMapper { get; protected set; }

        public MyBatis_Repository(ISqlMapper sqlMapper)
        {
            SqlMapper = sqlMapper;
        }

        public virtual int Insert<T>(string statementName, T t)
        {
            return (int)SqlMapper.Insert(statementName, t);
        }

        public virtual int Update<T>(string statementName, T t)
        {
            return SqlMapper.Update(statementName, t);
        }

        public virtual int Delete(string statementName, int primaryKeyId)
        {
            return SqlMapper.Delete(statementName, primaryKeyId);
        }

        public virtual T Get<T>(string statementName, int primaryKeyId) where T : class
        {
            return SqlMapper.QueryForObject<T>(statementName, primaryKeyId);
        }

        public virtual IList<T> QueryForList<T>(string statementName, object parameterObject = null)
        {
            return SqlMapper.QueryForList<T>(statementName, parameterObject);
        }

        /// <summary>
        /// 获取运行时SQL语句
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="parameterObject"></param>
        /// <returns></returns>
        protected string GetRuntimingSql(string statementName, object parameterObject = null)
        {
            string sql = string.Empty;

            try
            {
                IMappedStatement statement = SqlMapper.GetMappedStatement(statementName);
                if (!SqlMapper.IsSessionStarted)
                {
                    SqlMapper.OpenConnection();
                }
                RequestScope scope = statement.Statement.Sql.GetRequestScope(statement, parameterObject, SqlMapper.LocalSession);
                sql = scope.PreparedStatement.PreparedSql;
            }
            catch(Exception ex)
            {
                sql = "获取SQL语句出现异常:" + ex.Message;
            }

            return sql;
        }
    }
}